import urllib
import aioredis
import aiohttp
import lxml.html
import json
import asyncio
import time
import random

import re
from PIL import Image
import io
import logging
import sys
import os
sys.path.append(os.path.abspath('../'))
from util.cmcc_10086 import aget_llqrcode

logger = logging.getLogger("cmcc")


def get_uuid():
    token = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
    new_token = ""
    for i in  token:
        r = int(random.random() * 16) | 0
        if i == 'x':
            new_token += "%x" % r
        elif i == 'y':
            new_token += "%x" % (r&0x3|0x8)
        else:
            new_token += i
    return new_token

def get_ts():
    return str(time.time()).replace('.', '')[:13]

async def get_weixin_h5(tel, amount, redis, channel="wx", ip=None):
    res = await aget_llqrcode(tel, amount, redis)
    if res["retCode"] != "000000":
        logger.info("%s不可交费", tel)
        return {'code': -1}
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
    if ip:

        headers.update({
            'CLIENT-IP': ip,
            'X-FORWARDED-FOR': ip
        })

    proxys = await redis.smembers('un_proxy', encoding='utf-8')
    # proxy = random.choice([p for p in proxys if '@' not in p and '16817' not in p])
    proxy = random.choice([p for p in proxys if '@' not in p])
    logger.info("%s|%s", tel, proxy)
    if proxy:
        conn = proxy
    else:
        conn = None
    # conn = None
    async with aiohttp.ClientSession(headers=headers) as session:

        url = 'https://dev.10086.cn/api/accessURL?sspId=63861&pageId=P170808008'
        async with session.get(url, proxy=conn, headers=headers) as rsp:
            text = await rsp.text()

        url = 'https://open.10086.cn/h5/common/pageInfo?pageId=P170808008'
        async with session.get(url, proxy=conn) as rsp:
            goods_infos = await rsp.json()
            # print(goods_infos)
            goods_id = ""
            for g in goods_infos['data']['pageInfo']['goods'][0]['goodsRule']:
                if amount == g['price']:
                    goods_id = g['goodsId']
            if not goods_id:
                return {"code": -1, "message": goods_infos['bizDesc']}
            activity_id = goods_infos['data']['pageInfo']['actives'][goods_id][0]['activityId']
        data = {
            'activityId': activity_id,
            'goodsId': goods_id,
            'mobile': tel
        }
        # print(data)
        url = 'https://open.10086.cn/h5/buy/recharge/payment.html'
        async with session.get(url, proxy=conn, params=data) as rsp:
            text = await rsp.text()
            # print(text)
        url = 'https://open.10086.cn/h5/activity/isJoinActivity'

        async with session.post(url, proxy=conn, json=data) as rsp:
            text = await rsp.json()
            # print(text)
        url = 'https://open.10086.cn/h5/recharge/order'
        data = {
            'activityId': activity_id,
            'goodsId': goods_id,
            'mobile': tel,
            'paymentType': 'WEIXIN-WAP',
            'rechargeType': 'phoneBill',
            'smsCode': None
        }
        async with session.post(url, proxy=conn, json=data) as rsp:
            text = await rsp.json()
            logger.info(text)
            data = text['data']['payForm']
            pay_url = text['data']['payUrl']
            orderid = text['data']['payForm']['OrderNo']
            query_url = text['data']['payForm']['ReturnURL']

        # pay_url = 'https://pay.chinamobilesz.com/payprod-format/ownh5/submit.action'
        async with session.post(pay_url, proxy=conn, data=data) as rsp:
            text = await rsp.text()
            root = lxml.html.fromstring(text)
            ele = root.xpath("//form")
            url = ele[0].attrib.get('action')
            logger.info(url)
        headers['Referer'] = pay_url
        async with session.post(url, proxy=conn, headers=headers) as rsp:
            text = await rsp.text()
            wx_url = re.findall('"(weixin.*)"', text)
        logger.info(query_url)
        return {"code": 0, 'orderid': orderid, 'query_url': query_url, 'url': wx_url[0]}
        # async with session.get(query_url, proxy=conn) as rsp:
        #     text = await rsp.text()
        #     print(text)


async def cmcc_query(query_url, redis):

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
    proxys = await redis.smembers('un_proxy', encoding='utf-8')
    proxy = random.choice(list(proxys))
    logger.info(proxy)
    if proxy:
        conn = proxy
    else:
        conn = None
    # conn = None

    async with aiohttp.ClientSession(headers=headers) as session:
        url = "https://dev.10086.cn/api/accessURL?sspId=63861&pageId=P170808008"
        async with session.get(url, proxy=conn) as rsp:
            text = await rsp.text()


            # return orderstate,  message
        orderid = query_url.split('/')[-1]
        url = 'https://open.10086.cn/h5/payorder/status?orderId=%s' % orderid
        async with session.get(url, proxy=conn) as rsp:
            res = await rsp.json()
            # 02 2
            print(res)
            if res['data']['payStatus'] == "1":  # 01
                orderstate = "0"
            elif res['data']['payStatus'] == "3":  # "00"
                orderstate = '8'
            # elif res['data']['payStatus'] == "20":
            #     orderstate = '1'
            else:
                orderstate = '9'
            return orderstate, res['data']['statusDesc']



if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    now = time.time()
    redis = loop.run_until_complete(
        aioredis.create_redis(address=('localhost', 6379), db=0, loop=loop)
    )
    task = asyncio.ensure_future(get_weixin_h5("13418071372", "10", redis))
    # task = asyncio.ensure_future(cmcc_query("322018111618325377201158463", "13871137387", redis))
    print(loop.run_until_complete(task))
    print(time.time() - now)
    loop.close()
